import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'api_config.dart';
import 'package:pretty_dio_logger/pretty_dio_logger.dart';

class HttpReq {
  static final BaseOptions bashOptions = BaseOptions(
    baseUrl: ApiConfig.baseUrl,
    connectTimeout: ApiConfig.resquestTimeout,
  );
  static final Dio _dio = Dio(bashOptions);

  ///[url] 请求url
  ///[method] 请求方式
  ///[params] 请求参数
  ///[interceptor] 拦截器
  static Future<T> request<T>(String url,
      {String method = 'post', Map<String, dynamic>? params, Interceptor? interceptor}) async {
    //添加全局拦截器
    Interceptor dInter = InterceptorsWrapper(onRequest: (options, handler) {
      //请求拦截
      // you can resolve a `Response` using `handler.resolve(response)`.
      // you can reject with a `DioException` using `handler.reject(dioError)`.
      return handler.next(options);
    }, onResponse: (response, handler) {
      //响应拦截
      // you can reject a `DioException` object using `handler.reject(dioError)`
      return handler.next(response);
    }, onError: (error, handler) {
      //错误拦截
      // you can resolve a `Response` object using `handler.resolve(response)`.
      return handler.next(error);
    });

    //添加拦截器
    _dio.interceptors.clear();
    List<Interceptor> inters = [dInter];
    // 请求单独拦截器
    if (interceptor != null) {
      inters.add(interceptor);
    }
    ///////////////////PrettyDioLogger
    if (kDebugMode) {
      inters.add(PrettyDioLogger(
          requestHeader: true,
          requestBody: true,
          responseBody: true,
          responseHeader: false,
          error: true,
          compact: true,
          maxWidth: 90,
          enabled: kDebugMode,
          filter: (options, args) {
            // if (
            //     // options.path.contains(ApiConfig.register) ||
            //     // options.path.contains(ApiConfig.videoList) ||
            //     options.path.contains(ApiConfig.gameList)) {
            //   return true;
            //    }
            //  else {
            //   return false;
            // }
            return !args.isResponse || !args.hasUint8ListData;
          }));
    }
    ///////////////////PrettyDioLogger

    _dio.interceptors.addAll(inters);
    //发送网络请求
    final opt = Options(method: method);
    try {
      String? json;
      if (params != null) {
        try {
          json = jsonEncode(params);
        } catch (e) {
          json = null;
        }
      }
      Response response = await _dio.request(url, data: json, options: opt);
      return response.data;
    } on DioException catch (e) {
      return Future.error(e);
    }
  }
}
